package com.atguigu.com.gmall.index.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.com.gmall.index.annotation.GmallCache;
import com.atguigu.com.gmall.index.feign.pms.PmsClient;
import com.atguigu.com.gmall.index.service.IndexService;
import com.atguigu.gmall.common.bean.ResponseVo;
import com.atguigu.gmall.pms.entity.CategoryEntity;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class IndexServiceImpl implements IndexService {

    @Autowired
    PmsClient pmsClient;

    @Autowired
    StringRedisTemplate redisTemplate;

    private static final String KEY_PREFIX = "index:cates:";

    private static final String LOCK_PREFIX = "index:cates:lock:";

    @Override
    public List<CategoryEntity> queryLvl1Categories(long l) {
        ResponseVo<List<CategoryEntity>> listResponseVo = pmsClient.queryCategoriesByPid(l);
        List<CategoryEntity> data = listResponseVo.getData();
        return data;
    }

    /*
    二三级缓存
     */
    @Override
    @GmallCache(prefix = KEY_PREFIX, timeout = 129600, random = 14400, lock = LOCK_PREFIX)
    public List<CategoryEntity> queryLvl12CategoriesByPid(Long pid) {
        //首先从redis缓存中查询数据
//        String json = redisTemplate.opsForValue().get(KEY_PREFIX + pid);
//        if (StringUtils.isNotBlank(json)){
//            return JSON.parseArray(json,CategoryEntity.class);
//        }
        //缓存不存在 从数据库中查询
        //加锁
//        String uuid = UUID.randomUUID().toString();
//        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", uuid, new Random().nextInt(10), TimeUnit.MINUTES);
//        if (lock){
//
//        }
        ResponseVo<List<CategoryEntity>> listResponseVo = pmsClient.queryLvl12CategoriesByPid(pid);
        List<CategoryEntity> data = listResponseVo.getData();
//        if (!CollectionUtils.isEmpty(data)){
//            redisTemplate.opsForValue().set(KEY_PREFIX+pid,JSON.toJSONString(data));
//        }else {
//            //设置一个任意值防止缓存击穿
//        }
        return data;
    }
}
